package com.alliky.core.base

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.alliky.common.entity.MessageEvent
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.lang.ref.WeakReference

abstract class BasicFragment : Fragment() {

    private var mContext: WeakReference<Context>? = null

    abstract fun setLayout(): Any?

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        val rootView: View? = if (setLayout() is Int) {
            inflater.inflate(setLayout() as Int, container, false)
        } else if (setLayout() is View) {
            setLayout() as View?
        } else {
            throw ClassCastException("type of setLayout() must be int or View!")
        }


        return rootView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        if (useEventBus() && !EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        mContext = WeakReference(activity)
        initView()
        initData()
    }

    override fun getContext(): Context? {
        return mContext?.get()
    }

    /**
     * 初始化 View
     */
    abstract fun initView()

    /**
     * 初始化数据
     */
    abstract fun initData()

    /**
     * 是否使用 EventBus
     */
    open fun useEventBus(): Boolean = true

    @Subscribe(threadMode = ThreadMode.MAIN)
    open fun onEvent(message: MessageEvent) {
    }

    override fun onDestroy() {
        super.onDestroy()
        if (useEventBus() && EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
    }

    open fun isBackPressed(): Boolean {
        return false
    }
}